// cloudfunctions/getPriceTrend/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
  })
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { productId } = event;
    if (!productId) {
      return { success: false, message: '缺少productId参数' };
    }
    
    // 计算近七天的日期范围
    const now = new Date();
    const sevenDaysAgo = new Date(now);
    sevenDaysAgo.setDate(now.getDate() - 7);
    
    console.log('查询时间范围:', sevenDaysAgo, now);
    
    // 替代聚合方法：使用普通查询并在代码中处理分组
    const result = await db.collection('blindbox_goods')
      .where({
        productId: productId,
        createTime: _.gte(sevenDaysAgo).lte(now)
      })
      .get();
    
    const goodsList = result.data;
    console.log('查询到的商品数量:', goodsList.length);
    console.log('查询结果示例:', goodsList[0]);
    
    // 在代码中处理日期分组和计算平均价格
    const groupedByDate = {};
    
    goodsList.forEach(good => {
      // 确保createTime是Date对象
      const createTime = good.createTime instanceof Date 
        ? good.createTime 
        : new Date(good.createTime);
      
      // 格式化日期为YYYY-MM-DD格式
      const dateKey = `${createTime.getFullYear()}-${
        String(createTime.getMonth() + 1).padStart(2, '0')}-${
        String(createTime.getDate()).padStart(2, '0')}`;
      
      // 初始化日期组
      if (!groupedByDate[dateKey]) {
        groupedByDate[dateKey] = {
          totalPrice: 0,
          count: 0
        };
      }
      
      // 累加价格和计数
      groupedByDate[dateKey].totalPrice += good.goodsPrice;
      groupedByDate[dateKey].count++;
    });
    
    // 计算每个日期的平均价格
    const dailyAvgPrices = Object.keys(groupedByDate).map(dateKey => {
      const group = groupedByDate[dateKey];
      return {
        dateString: dateKey,
        avgPrice: parseFloat((group.totalPrice / group.count).toFixed(2)),
        count: group.count
      };
    });
    
    // 按日期排序
    dailyAvgPrices.sort((a, b) => new Date(a.dateString) - new Date(b.dateString));
    
    console.log('按日期分组的平均价格:', dailyAvgPrices);
    
    // 格式化数据，生成适合Canvas折线图的数据结构
    const formattedData = formatChartData(dailyAvgPrices, sevenDaysAgo, now);
    
    return {
      success: true,
      data: formattedData,
      message: '获取价格趋势成功'
    };
  } catch (error) {
    console.error('获取价格趋势失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};

// 格式化数据为图表可用格式
function formatChartData(aggregationResult, startDate, endDate) {
  // 创建完整的日期范围数组
  const dates = [];
  const currentDate = new Date(startDate);
  
  while (currentDate <= endDate) {
    dates.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }
  
  // 日期格式化函数
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  
  // 构建图表数据
  const chartData = {
    labels: dates.map(date => formatDate(date)), // X轴标签：日期
    details: aggregationResult.map(item => ({
      date: item.dateString,
      avgPrice: item.avgPrice,
      count: item.count
    }))
  };
  
  return chartData;
}